import csv
import os
from datetime import datetime
from typing import Union

'''
获取股市开市以来的交易日
'''


def convert_to_date(d: Union[str, datetime]) -> datetime:
    """将输入转换为datetime.date对象"""
    if isinstance(d, str):
        return datetime.strptime(d, '%Y-%m-%d')
    elif isinstance(d, datetime):
        return d
    else:
        raise TypeError(f"日期必须是字符串或datetime.date对象，而不是 {type(d)}")


def get_trading_calendar(start_date, end_date):
    """
    获取交易日历（使用真实交易日）
    """
    # 获取当前工作目录 (Current Working Directory)
    current_path = os.getcwd()
    print("当前工作路径:", current_path)
    print("当前文件路径:", __file__)
    # 获取当前脚本所在的文件夹路径
    script_dir = os.path.dirname(os.path.abspath(__file__))
    print("当前文件所在文件夹:", script_dir)

    trading_dates = []
    filename = 'trading_days.csv'
    abs_filename = os.path.join(script_dir, filename)
    try:
        with open(abs_filename, mode='r', encoding='utf-8') as file:
            reader = csv.reader(file)
            for row in reader:
                # 跳过空行和可能的标题行
                if not row or row[0].lower() == 'trade_date':
                    continue

                try:
                    # 解析日期字符串为datetime.date对象
                    date_obj = datetime.strptime(row[0], '%Y-%m-%d')
                    trading_dates.append(date_obj)
                except ValueError as e:
                    print(f"警告: 跳过无效日期格式 '{row[0]}' - {str(e)}")

    except FileNotFoundError:
        print(f"错误: 文件 '{abs_filename}' 未找到")
    except Exception as e:
        print(f"读取文件时发生错误: {str(e)}")

    return filter_dates_by_range(trading_dates, start_date, end_date)


def filter_dates_by_range(date_list, start_date, end_date):
    """
    从日期列表中筛选出指定日期范围内的日期

    参数:
        date_list (list): 日期字符串列表，格式为'YYYY-MM-DD'
        start_date (str): 开始日期，格式为'YYYY-MM-DD'
        end_date (str): 结束日期，格式为'YYYY-MM-DD'

    返回:
        list: 在[start_date, end_date]区间内的日期列表
    """
    try:
        # 转换输入日期
        start_dt = convert_to_date(start_date)
        end_dt = convert_to_date(end_date)

        # 筛选日期
        filtered_dates = [
            dt for dt in date_list
            if start_dt <= dt <= end_dt
        ]

        return filtered_dates

    except ValueError as e:
        print(f"日期格式错误: {e}")
        return []
    except Exception as e:
        print(f"发生错误: {e}")
        return []


# 示例使用
if __name__ == "__main__":
    # 示例日期列表
    dates = [
        datetime(1990, 12, 19), datetime(1990, 12, 20), datetime(1990, 12, 21),
        datetime(1990, 12, 24), datetime(1990, 12, 25), datetime(1990, 12, 26),
        datetime(1990, 12, 27), datetime(1990, 12, 28), datetime(1990, 12, 31),
        datetime(1991, 1, 2), datetime(1991, 1, 3), datetime(1990, 12, 23)
    ]

    # 测试筛选
    start = "1990-12-21"
    end = "1990-12-26"
    result = filter_dates_by_range(dates, start, end)
    print(f"原始日期列表: {dates}")
    print(f"筛选范围: {start} 到 {end}")
    print(f"筛选结果: {result}")

    result = get_trading_calendar(start, end)
    print(f"筛选范围: {start} 到 {end}")
    print(f"筛选结果: {result}")
